<template>
  <div :class="{ 'history-list-container': true, fold: !isShowHistory }">
    <div class="section-header">
      <span v-show="isShowHistory" class="count"
        >更改数（{{ historyList && historyList.length }}）</span
      >
      <a-icon-font
        class="icon"
        type="iconicon-beifen-right"
        @click="toggleDisplayMode"
      />
    </div>
    <div class="content">
      <template v-if="historyList && historyList.length > 0">
        <div
          v-for="item in historyList"
          :key="item.data.id"
          :class="{
            list: true,
            active: item.data.id === currentHistory.data.id,
            error: item.data.status !== 'SUCCESS',
          }"
          @click="setActive(item)"
        >
          <div class="icon">
            <a-icon-font
              v-if="item.data.status === 'SUCCESS'"
              :type="
                filterActionIconType[
                  item.data.actionType || item.data.action
                ] || 'iconqingxi-copy'
              "
            />
            <a-icon-font v-else type="iconwuquanxian" />
          </div>
          <div class="list-content">
            <div class="title">{{ item.data.label }}</div>
            <div
              class="description"
              :title="
                item.data.label === '原始数据'
                  ? item.data.label
                  : `${item.data.col ? item.data.col + '：' : ''}${
                      item.data.description
                    }`
              "
            >
              {{
                item.data.label === '原始数据'
                  ? `${item.data.label}`
                  : `${item.data.col ? item.data.col + '：' : ''}${
                      item.data.description
                    }`
              }}
            </div>
            <div
              v-if="item.data.status !== 'SUCCESS'"
              class="error-message"
              :title="JSON.parse(item.data.logInfo).error_msg"
            >
              {{ JSON.parse(item.data.logInfo).error_msg }}
            </div>
            <div v-show="item.data.label !== '原始数据'" class="btn-box">
              <!-- <a-icon-font
                v-show="isShowEditButton(item)"
                class="btn"
                type="iconicon-beifen6"
                @click="onEditHistory($event, item)"
              /> -->
              <a-icon-font
                class="btn"
                type="iconicon-beifen1"
                @click="onDeleteHistory($event, item)"
              />
            </div>
          </div>
        </div>
      </template>
      <template v-else>
        <div class="empty-info">无数据更改</div>
      </template>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Prop } from 'vue-property-decorator'
import {
  StatisticsAction,
  DisableEditAction,
} from '@/util/data-selection-actions'
import GraphBuild, { IKeyValueStore } from '@/store/modules/graphbuild'
import GraphViewStore from '@/store/modules/graphview'
import { tcolumnQueryDetail } from '@/api/visualization'
import noPermissionPrompt from '@/components/graph/user-permissions'

const disableEditAction = new Set(DisableEditAction) // 不可编辑的actionType

/**
 * 数据action对应的图标
 */
const filterActionIconType = {
  ORIGINAL_DATA: 'iconshujubiao',
  [StatisticsAction.filterNull]: 'iconnullzhishaixuan',
  [StatisticsAction.filterWildcard]: 'icontongpeifushaixuan',
  [StatisticsAction.filterSelected]: 'icontedingzhishaixuan',
  [StatisticsAction.filterNumberRange]: 'iconshaixuanshuzhifanwei',
  [StatisticsAction.filterDateRange]: 'iconriqifanweishaixuan',
  [StatisticsAction.deleteColumn]: 'iconshanchuziduan',
  [StatisticsAction.copyColumn]: 'iconfuzhiziduan',
  [StatisticsAction.typeTransform]: 'icongenggaiziduanleixing',
  [StatisticsAction.partitionBy]: 'iconfenzu',
  [StatisticsAction.lowerCase]: 'icongaiweixiaoxie',
  [StatisticsAction.upperCase]: 'icongaiweidaxie',
  [StatisticsAction.splitColumn]: 'iconziduanchaifen',
  [StatisticsAction.mergeColumn]: 'iconhebing',
  [StatisticsAction.removeLetter]: 'iconyichuzimu',
  [StatisticsAction.removeNumber]: 'iconyichushuzi',
  [StatisticsAction.removePunctuation]: 'iconyichubiaodian',
  [StatisticsAction.renameColumn]: 'iconzhongmingming',
  [StatisticsAction.keepOnlyColumn]: 'iconjinbaoliugailie',
  [StatisticsAction.trimSpace]: 'iconcaijiankongge',
  [StatisticsAction.removeAllSpace]: 'iconyichusuoyoukongge',
  [StatisticsAction.cleanFromVis]: 'iconkeshihuaqingxi',
  MORE_ICON: 'icongengduocaozuo',
}

@Component({})
export default class GraphNodeHistoryList extends Vue {
  @Prop() isShowHistory: boolean = false
  @Prop() graphId: number = 0

  // 是否没有编辑权限（图构建创建者）
  public get isGraphSelfCreate() {
    return GraphBuild.isGraphSelfCreate
  }

  // private currentHistoryItem: IKeyValueStore = []

  private get filterActionIconType() {
    return filterActionIconType
  }

  public get historyList() {
    return GraphBuild.currentNodeHistory.historyList
  }

  private get currentHistory() {
    return GraphBuild.currentSelectedHistory || { data: {} }
  }

  private isShowEditButton(item: any) {
    let isShow = true
    if (
      disableEditAction.has(item.data.actionType) ||
      item.data.status !== 'SUCCESS'
    ) {
      // 新增当清洗记录是-根据示例新增列的情况时
      isShow = false
    }
    return isShow
  }

  toggleDisplayMode() {
    this.$emit('toggle-history-mode', false)
  }

  /**
   * 需要根据当前选中的历史条目重新请求数据
   */
  async refreshTableData(history: IKeyValueStore, callback?: Function) {
    const response = await tcolumnQueryDetail({
      data: {
        table: history && history.data.table,
      },
    })
    this.$emit('update-table', history.data.table)
    const result = response.data.result || {}
    // console.log(result)
    // console.log(history)
    GraphViewStore.setTableData({
      head: result.head || [],
      data: result.data || [],
    })
    GraphBuild.setCurrentSelectedHistory(history)
    if (callback) {
      callback()
    }
  }

  /**
   * 设置操作历史选择态
   */
  setActive(history: IKeyValueStore) {
    if (history.data.status !== 'SUCCESS') {
      return
    }
    // GraphBuild.setCurrentSelectedHistory(history)
    if (history.data.id !== this.currentHistory.data.id) {
      this.refreshTableData(history)
    }
  }

  /**
   * 删除操作历史记录
   */
  async onDeleteHistory(event: Event, history: IKeyValueStore) {
    if (!this.isGraphSelfCreate) {
      noPermissionPrompt()
      return
    }
    event.stopPropagation()
    const response = await GraphBuild.delHistory({
      graphId: this.graphId,
      id: history.data.id,
    })
    if (!response.success) {
      this.$message.error(response.message)
      return
    }
    this.$emit('delete-action', response.result)
    GraphViewStore.setCurrentCategoryData(response.result.category) // 删除历史记录后，将新数据保存回当前节点存储
    GraphBuild.setCurrentCategoryData(response.result.category) // 删除历史记录后，将新数据保存回当前节点存储
    GraphBuild.getHistoryList(this.graphId)
    this.$message.success('操作成功')
  }
}
</script>

<style lang="less" scoped>
.history-list-container {
  background-color: #fff;
  // border-top: 1px solid rgba(233, 233, 233, 0.8);
  height: 100%;
  width: 280px;

  .section-header {
    align-items: center;
    color: #373b52;
    display: flex;
    font-size: 14px;
    height: 38px;
    justify-content: space-between;
    padding: 0 10px 0 20px;
    width: 100%;

    .count {
      letter-spacing: 1.12px;
    }

    .icon {
      cursor: pointer;
      padding: 8px;
      transform: rotate(180deg);
    }
  }

  .content {
    background-color: #fff;
    height: calc(100% - 38px);
    overflow-y: auto;

    .list {
      display: flex;
      padding: 8px 10px 8px 16px;

      &.active {
        background-color: #eff0fe;
      }

      &.error {
        .list-content,
        .list-content .title {
          color: #f26740;
        }
      }

      .icon {
        margin-right: 10px;
        position: relative;
      }

      .icon::after {
        background-color: #d8d8d8;
        bottom: -1px;
        content: '';
        display: block;
        height: 16px;
        left: 6px;
        position: absolute;
        width: 1px;
      }

      .list-content {
        color: rgba(34, 36, 50, 0.6);
        flex: 1;
        font-size: 12px;
        letter-spacing: 1.12px;
        overflow: hidden;
        position: relative;
        text-overflow: ellipsis;
        white-space: nowrap;

        .title {
          color: #373b52;
          font-size: 14px;
          width: 180px;
        }

        .title,
        .description {
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }

        .btn-box {
          color: #5d637e;
          cursor: pointer;
          display: none;
          font-size: 16px;
          position: absolute;
          right: 0;
          top: 0;

          .btn {
            margin-right: 8px;
          }
        }

        &:hover .btn-box {
          display: block;
        }
      }
    }
  }

  .empty-info {
    color: rgba(34, 36, 50, 0.6);
    padding-top: 32px;
    text-align: center;
  }

  &.fold {
    width: 44px;

    .section-header {
      border-bottom: 0;
      height: auto;
      letter-spacing: 8px;
      padding: 10px 0;
      writing-mode: vertical-lr;
    }

    .icon {
      transform: rotate(0);
    }
  }
}
</style>
